package cn.anline.ann.auto_hid_control

import android.content.Intent
import android.icu.text.SimpleDateFormat
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import cn.anline.ann.auto_hid_control.senders.KeyboardSender
import cn.anline.ann.auto_hid_control.service.AutoHIDSenderService
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.disposables.Disposable
import java.util.*
import java.util.concurrent.TimeUnit

class MainActivity : AppCompatActivity() {

    private lateinit var leftSecondTV: TextView
    private lateinit var startBtn: Button
    private lateinit var startSrvBtn: Button
    private lateinit var subscribe: Disposable
    private var times = 0

    private var isSrvStart = false
    private var isStart = false

    private var rKeyboardSender: KeyboardSender? = null

    private var ctrPeriod = 5L  // 间隔时间 s 秒

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        leftSecondTV = findViewById(R.id.leftSecond)
        startBtn = findViewById(R.id.startBtn)
        startSrvBtn = findViewById(R.id.startSrvBtn)
        findViewById<TextView>(R.id.currentPeroid).text = "默认间隔秒数${ctrPeriod}"
        initBluetooth()
    }

    fun initBluetooth() {
        BluetoothController.init(this)
        BluetoothController.getSender { hidd, device ->
            Log.wtf("weiufhas", "Callback called")
            val mainHandler = Handler(applicationContext.mainLooper)

            mainHandler.post(object : Runnable {
                override fun run() {
                    rKeyboardSender = KeyboardSender(hidd, device)
                    //------------trackPadView.setOnTouchListener(viewTouchListener)
                }
            })
        }

        BluetoothController.getDisconnector {
            val mainHandler = Handler(applicationContext.mainLooper)

            mainHandler.post(object : Runnable {
                override fun run() {

                }
            })
        }
    }

    fun startSender() {
        subscribe = Flowable.interval(ctrPeriod, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                println("定时器：${Date().toInstant()}")
                if (rKeyboardSender != null) {
                    var rvalue: Boolean? = false
                    val ke = KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_RIGHT)
                    rvalue = rKeyboardSender?.sendKeyboard(
                        KeyEvent.KEYCODE_DPAD_RIGHT,
                        ke,
                        0
                    )
                    if (rvalue == true) {
                        println("键盘发送器：发送成功")
                    } else {
                        println("键盘发送器：发送失败")
                    }
                } else {
                    println("无法获取键盘发送器")
                }
                times += 1
                leftSecondTV.text =
                    "第 ${times} 次翻页，时间：${SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date().time)}"
            }
    }


    fun onStartBtnClick(view: View) {

        if (isStart) {
            isStart = false
            subscribe.dispose()
            leftSecondTV.text = "翻页已停止，已执行次数${times}"
            times = 0
            startBtn.text = "开启翻页"
        } else {
            if (rKeyboardSender == null) {
                leftSecondTV.text = "无法获取连接，请先打开本APP后，打开系统>蓝牙>连接需要控制的设备，然后打开需要自动翻页的电子书页面即可自动翻页"
                startBtn.text = "重启翻页"
                return
            }
            startSender()
            isStart = true
            startBtn.text = "停止翻页"
        }
    }

    fun onStartSrvBtnClick(view: View) {
        Toast.makeText(this, "服务功能开发中...", Toast.LENGTH_SHORT).show()
        return
        if (isSrvStart) {
            isSrvStart = false
            stopService(Intent(this, AutoHIDSenderService::class.java))
            startSrvBtn.text = "开启服务"
        } else {
            isSrvStart = true
            startService(Intent(this, AutoHIDSenderService::class.java))
            startSrvBtn.text = "停止服务"
        }

    }

    fun onSetPeriodSecond(view: View) {
        ctrPeriod = findViewById<EditText>(R.id.et_peroid_second).text.toString().toLong()
        findViewById<TextView>(R.id.currentPeroid).text = "当前间隔秒数${ctrPeriod}"
    }

}